package public

import (
	"NovelBook/logic/book"
	"NovelBook/models/db_models"
	"NovelBook/utils/response"
	"log"
	"strconv"

	"github.com/gin-gonic/gin"
)

func Search(c *gin.Context) {
	query := c.Query("id")
	if len(query) != 0 {
		SearchBookById(c)
		return
	}

	query = c.Query("isbn")
	if len(query) != 0 {
		SearchBookByIsbn(c)
		return
	}

	query = c.Query("name")
	if len(query) != 0 {
		SearchBookByName(c)
		return
	}
	query = c.Query("wd")
	if len(query) != 0 {
		SearchFaintly(c)
		return
	}
	query = c.Query("author")
	if len(query) != 0 {
		SearchBookByAuthor(c)
		return
	}
	query = c.Query("publisher")
	if len(query) != 0 {
		SearchBookByPublisher(c)
		return
	}
}
func SearchBookById(c *gin.Context) {
	query := c.Query("id")
	bookId, err := strconv.Atoi(query)
	if err != nil {
		response.FailWithMsg(c, 400, 1001, "ID error")
		return
	}
	var books []db_models.Books
	books, err = book.SearchBookById(bookId)
	if err != nil {
		log.Println(err)
		return
	}
	response.Success(c, books)
	return
}

func SearchBookByIsbn(c *gin.Context) {
	query := c.Query("isbn")
	if len(query) == 0 {
		return
	}
	books, err := book.SearchBookByIsbn(query)
	if err != nil {
		log.Println(err)
		return
	}
	response.Success(c, books)
	return
}
func SearchBookByName(c *gin.Context) {
	query := c.Query("name")
	if len(query) == 0 {
		return
	}
	books, err := book.SearchBookByName(query)
	if err != nil {
		log.Println(err)
		return
	}
	response.Success(c, books)
	return
}
func SearchBookByAuthor(c *gin.Context) {
	query := c.Query("author")
	if len(query) == 0 {
		return
	}
	books, err := book.SearchBookByAuthor(query)
	if err != nil {
		log.Println(err)
		return
	}
	response.Success(c, books)
	return
}
func SearchBookByPublisher(c *gin.Context) {
	query := c.Query("publisher")
	if len(query) == 0 {
		return
	}
	books, err := book.SearchBookByPublisher(query)
	if err != nil {
		log.Println(err)
		return
	}
	response.Success(c, books)
	return
}
func SearchBookByKind(c *gin.Context) {
	query := c.Query("Kind")
	if len(query) == 0 {
		return
	}
	books, err := book.SearchBookByKind(query)
	if err != nil {
		log.Println(err)
		return
	}
	response.Success(c, books)
	return

}
